﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Xml.Serialization;

namespace TfL
{
    public interface IStationStatusFeed : ITrackerNetFeed<List<StationStatus>>
    {
        StationStatusFeed IncidentsOnly { get; }
    }

    public class StationStatusFeed : IStationStatusFeed, IDisposable
    {
        public StationStatusFeed(string url,string ns)
        {
            _feed = new TrackerNetFeed<List<StationStatus>>(url, ns);
            _feed.DecodeResponse += DecodeResponse;
            Url += "/StationStatus";
        }

        public StationStatusFeed IncidentsOnly 
        { 
            get
            {
                Url += "/IncidentsOnly";
                return this;
            }
        }

        private void DecodeResponse(WebResponse response)
        {
            //StreamReader reader = new StreamReader(response.GetResponseStream());
            //string text = reader.ReadToEnd();
            var serializer = new XmlSerializer(typeof(List<StationStatus>), Ns);
            if (response != null)
            {
                OnNext(null);
                var statusList = (List<StationStatus>)serializer.Deserialize(response.GetResponseStream());
                OnNext(statusList);
                
            }
        }

        #region ITrackerNetFeed<List<StationStatus>> Members

        public string Ns
        {
            get { return _feed.Ns; }
        }

        public string Url
        {
            get{return _feed.Url;}
            set{_feed.Url = value;}
        }

        #endregion

        #region IObserver<List<StationStatus>> Members

        public void OnCompleted()
        {
            _feed.OnCompleted();
        }

        public void OnError(Exception error)
        {
            _feed.OnError(error);
        }

        public void OnNext(List<StationStatus> value)
        {
            _feed.OnNext(value);
        }

        #endregion

        #region IObservable<List<StationStatus>> Members

        public IDisposable Subscribe(IObserver<List<StationStatus>> observer)
        {
            return _feed.Subscribe(observer);
        }

        #endregion

        #region ITrackerNetFeedPoller<List<StationStatus>> Members

        public System.Reactive.Subjects.ISubject<List<StationStatus>> Poll()
        {
            return _feed.Poll();
        }

        public System.Reactive.Subjects.ISubject<List<StationStatus>> Poll(System.Threading.CancellationToken token, int period)
        {
            return _feed.Poll(token, period);
        }

        #endregion

        private readonly TrackerNetFeed<List<StationStatus>> _feed;

        #region IDisposable Members

        public void Dispose()
        {
            _feed.DecodeResponse -= DecodeResponse;
        }

        #endregion
    }
}
